package part18;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author wcj
 * @Date 2021/6/4 15:23
 * @Version 1.0
 */
public class Part1821 {

    private static final int SIZE = 1024;

    /**
     * 利用新IO复制数据
     * 这里我们创建一个ByteBuffer
     * 每次从流中读取数据放入缓冲时，需要我们调用缓冲区的flip方法，让缓冲区准备好去写出
     * 每次写出之后需要我们对缓冲区进行清理，方便下一次的缓冲区的使用
     *
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        FileChannel in = new FileInputStream("data.txt").getChannel();
        FileChannel out = new FileOutputStream("data2.txt").getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(SIZE);
        while ((in.read(buffer) != -1)) {
            buffer.flip();
            out.write(buffer);
            buffer.clear();
        }
    }

    /**
     * 可以使用FileInputStream的channel的transferTo()方法或者
     * FileOutputStream的channel的transferFrom()方法直接将两个通道进行相联
     *
     * @throws IOException
     */
    public static void test() throws IOException {
        FileChannel in = new FileInputStream("data.txt").getChannel();
        FileChannel out = new FileOutputStream("data2.txt").getChannel();
        in.transferTo(0, in.size(), out);
//        out.transferFrom(in, 0, in.size());
    }
}
